package pers.zc.activiti.thread.pool;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @description 线程池
 * @Author Lin FuYuan
 * @date 2020/3/27
 */
@Configuration
public class ThreadPool {
    /**线程池配置属性*/
    private static final int CORE_POOL_SIZE = 10;
    private static final int MAX_POOL_SIZE = 20;
    private static final int KEEP_ALIVE_SECONDS = 10;
    private static final int QUEUE_CAPACITY = 10;
    private static final String THREAD_NAME_HEAD = "TestThread-";

    /**
     * 1.这种形式的线程池配置是需要在使用的方法上面@Async("taskExecutor"),
     * 2.如果在使用的方法上面不加该注解那么spring就会使用默认的线程池
     * 3.所以如果加@Async注解但是不指定使用的线程池，又想自己定义线程池那么就可以重写spring默认的线程池
     * 4.所以第二个方法就是重写默认线程池
     * 注意：完全可以把线程池的参数写到配置文件中
     */
    @Bean
    public ThreadPoolTaskExecutor testThreadPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CORE_POOL_SIZE);
        //核心线程池大小
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        //最大线程数
        executor.setQueueCapacity(QUEUE_CAPACITY);
        //队列容量
        executor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS);
        //活跃时间
        executor.setThreadNamePrefix(THREAD_NAME_HEAD);
        //线程名字前缀
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //当pool已经到达max size的时候，如何处理新任务,CallerRunsPolicy,由调用者所在的线程执行
        executor.setAllowCoreThreadTimeOut(true);
        executor.initialize();
        return executor;
    }

}
